<?php

namespace seraph_pds;

// #######################################################################

require_once( ABSPATH . 'wp-includes/pluggable.php' );

// #######################################################################
// #######################################################################

function _api_ProcessRequest( $action )
{
//	require_once( ABSPATH . 'wp-admin/includes/admin.php' );

	if( !current_user_can( "publish_posts" ) )
	{
		echo( wp_json_encode( array( "status" => "accessdenied" ) ) );
		return;
	}

	switch( $action )
	{
	case "updatePostInfo":
		$data = file_get_contents( 'php://input' );
		if( empty( $data ) )
		{
			echo( wp_json_encode( array( "status" => "invaliddata" ) ) );
			return;
		}

		$data = json_decode( $data, true );
		if( !$data )
		{
			echo( wp_json_encode( array( "status" => "fail", "status_descr" => "Data JSON parse: " . json_last_error_msg() ) ) );
			return;
		}

		$post = null;
		$postId = 0;
		{
			if( isset( $_REQUEST[ 'id' ] ) )
			{
				$postId = $_REQUEST[ 'id' ];
				$post = get_post( $postId );
				if( !$post )
				{
					echo( wp_json_encode( array( "status" => "notfound" ) ) );
					return;
				}

				if( $post -> post_type != $_REQUEST[ 'type' ] )
				{
					echo( wp_json_encode( array( "status" => "wrongtype" ) ) );
					return;
				}
			}
			else
			{
				if( empty( $data[ 'title' ] ) )
					$data[ 'title' ] = 'New ' . $_REQUEST[ 'type' ];

				$postId = wp_insert_post( array( 'post_title' => wp_slash( $data[ 'title' ] ), 'post_type' => $_REQUEST[ 'type' ], 'post_content' => '', 'comment_status' => 'open' ) );
				if( !( $postId > 0 ) )
				{
					echo( wp_json_encode( array( "status" => "fail" ) ) );
					return;
				}

				unset( $data[ 'title' ] );

				$post = get_post( $postId );
			}
		}

		$arrWarn = array();
		$res = SetPostData( $post, $data, $arrWarn );

		echo( wp_json_encode( array( "status" => $res, "warnings" => $arrWarn, "data" => array( "id" => $postId, "mediaUrl" => _GetPostImagesUrl( $post ), "postUrl" => get_permalink( $post ) ) ) ) );
		break;

	case "updatePostData":
		$postId = $_REQUEST[ 'id' ];
		$post = get_post( $postId );
		if( empty( $post ) )
		{
			echo( wp_json_encode( array( "status" => "notfound" ) ) );
			return;
		}

		$data = file_get_contents( 'php://input' );
		if( empty( $data ) )
		{
			echo( wp_json_encode( array( "status" => "invaliddata" ) ) );
			return;
		}

		$data = json_decode( $data, true );
		if( !$data )
		{
			echo( wp_json_encode( array( "status" => "fail", "status_descr" => "Data JSON parse: " . json_last_error_msg() ) ) );
			return;
		}

		$arrWarn = array();
		$res = SetPostData( $post, $data, $arrWarn );

		echo( wp_json_encode( array( "status" => $res, "warnings" => $arrWarn ) ) );
		break;

	case "sanitizeLabel":
		echo( sanitize_title( $_REQUEST[ "str" ] ) );
		break;

	case "getAttachmentIdFromUrl":
		echo( _GetAttachmentIdFromUrl( $_REQUEST[ "url" ] ) );
		break;

	case "getUrl":
		echo( getUrl( $_REQUEST[ 'url' ], !empty( $_REQUEST[ 'body' ] ) ) );
		break;

	case "uploadImage":
		$data = fopen( 'php://input', 'rb' );

		$res = UploadImage( $_REQUEST[ 'filename' ], $_REQUEST[ 'contentType' ], $data, $_REQUEST[ 'postId' ], isset( $_REQUEST[ 'addToAttachments' ] ), isset( $_REQUEST[ 'overwrite' ] ) );
		if( !is_wp_error( $res ) )
			echo( wp_json_encode( array( 'status' => 'ok', 'url' => $res ) ) );
		else
			echo( wp_json_encode( array( 'status' => $res -> get_error_code(), 'status_descr' => $res -> get_error_message() ) ) );

		fclose( $data );
		break;

	default:
		echo( wp_json_encode( array( "status" => "invalidarg" ) ) );
		break;
	}
}

// #######################################################################

function SetPostData( $post, $data, &$arrWarn )
{
	$availablePlugins = Plugin::GetAvailablePlugins();

	{
		$argsUpdatePost = array( "ID" => $post -> ID );

		// Title
		{
			$title = $data[ 'title' ];
			if( $title )
				$argsUpdatePost[ 'post_title' ] = $title;
		}

		// Slug
		{
			$slug = $data[ "slug" ];
			if( $slug )
				$argsUpdatePost[ "post_name" ] = $slug;
		}

		// Excerpt
		{
			$excerpt = $data[ "excerpt" ];
			if( $excerpt )
				$argsUpdatePost[ "post_excerpt" ] = $excerpt;
		}

		// Body
		{
			$text = $data[ "text" ];
			if( $text )
				$argsUpdatePost[ "post_content" ] = $text;
		}

		if( count( $argsUpdatePost ) > 1 )
		{
			$updRes = wp_update_post( wp_slash( $argsUpdatePost ) );
			if( is_wp_error( $updRes ) )
				return( "fail" );
		}
	}

	// Categories
	{
		$categories = $data[ "categories" ];
		if( $categories )
		{
			$applied = false;

			$postTypesTaxonomy = GetPostsTaxonomies( POSTS_TAXONOMY_META_CATEGORIES );
			if( !empty( $postTypesTaxonomy ) )
			{
				$postTaxonomy = $postTypesTaxonomy[ $post -> post_type ];
				if( !empty( $postTaxonomy ) )
				{
					wp_set_post_terms( $post -> ID, $categories, $postTaxonomy );
					$applied = true;
				}
			}

			if( !$applied )
				$arrWarn[] = 'categories_not_found';
		}
	}

	// Keywords
	{
		$keywords = $data[ "keywords" ];
		if( $keywords )
		{
			$applied = false;

			$postTypesTaxonomy = GetPostsTaxonomies( POSTS_TAXONOMY_META_TAGS );
			if( !empty( $postTypesTaxonomy ) )
			{
				$postTaxonomy = $postTypesTaxonomy[ $post -> post_type ];
				if( !empty( $postTaxonomy ) )
				{
					wp_set_post_terms( $post -> ID, $keywords, $postTaxonomy );
					$applied = true;
				}
			}

			if( !$applied )
				$arrWarn[] = 'keywords_not_set';
		}
	}

	// Featured Image
	{
		$featuredImage = $data[ "featuredImage" ];
		if( $featuredImage )
		{
			// set_post_thumbnail returns false if previous ID is equal to new one so check for 'false' is not needed
			set_post_thumbnail( $post, $featuredImage );
		}
	}

	// Title SEO
	{
		$titleSeo = $data[ "titleSeo" ];
		if( $titleSeo )
		{
			$bSet = false;

			// All in One SEO Pack
			if( in_array( 'all-in-one-seo-pack', $availablePlugins ) )
			{
				update_post_meta( $post -> ID, "_aioseop_title", $titleSeo );
				$bSet = true;
			}

			// Yoast SEO
			if( in_array( 'wordpress-seo', $availablePlugins ) )
			{
				update_post_meta( $post -> ID, "_yoast_wpseo_title", $titleSeo );
				$bSet = true;
			}

			if( !$bSet )
				$arrWarn[] = 'titleSeo_not_set';
		}
	}

	// Spec Descr
	{
		$descrSeo = $data[ "descrSeo" ];
		if( $descrSeo )
		{
			$bSet = false;

			// All in One SEO Pack
			if( in_array( 'all-in-one-seo-pack', $availablePlugins ) )
			{
				update_post_meta( $post -> ID, "_aioseop_description", $descrSeo );
				$bSet = true;
			}

			if( in_array( 'wordpress-seo', $availablePlugins ) )
			{
				update_post_meta( $post -> ID, "_yoast_wpseo_metadesc", $descrSeo );
				$bSet = true;
			}

			if( !$bSet )
				$arrWarn[] = 'descrSeo_not_set';
		}
	}

	// Custom attributes
	{
		$attrs = $data[ 'blocks' ];
		if( $attrs )
		{
			foreach( $attrs as $attrKey => $attr )
			{
				update_post_meta( $post -> ID, '_' . $attrKey, wp_slash( $attr ) );
			}
		}
	}

	return( "ok" );
}

function UploadImage( $fileName, $contentType, $data, $postId = 0, $addToAttachments = true, $overwrite = false )
{
	global $ctxUploadImage;

	$ctxUploadImage = array(
		'addToAttachments'		=> $addToAttachments,
		'overwrite'				=> $overwrite,
		'fileName'				=> $fileName,
	);

	if( !current_user_can( 'upload_files' ) )
		return( new WP_Error( 'access_denied', 'Current user can\'t upload files' ) );

	if( $postId && !current_user_can( 'edit_post', $postId ) )
		return( new WP_Error( 'access_denied', 'Current user can\'t edit the post' ) );

	global $post, $post_id;

	$post_prev = $post;
	$post_id_prev = $post_id;

	if( $postId )
	{
		$post = null;
		$post_id = $postId;
	}

	$fileNamePathTmp = wp_tempnam();

	add_filter( 'wp_unique_filename',			__NAMESPACE__ . '\\' . '_wp_unique_filename_UploadImage', 1, 4 );
	add_filter( 'pre_move_uploaded_file',		__NAMESPACE__ . '\\' . '_pre_move_uploaded_file_UploadImage', 1, 4 );
	add_filter( 'wp_handle_upload',				__NAMESPACE__ . '\\' . '_handle_upload_UploadImage', 1, 2 );

	$res = _UploadImage( $fileNamePathTmp, $fileName, $contentType, $data, $postId, $addToAttachments, $overwrite );

	remove_filter( 'wp_handle_upload',			__NAMESPACE__ . '\\' . '_handle_upload_UploadImage' );
	remove_filter( 'pre_move_uploaded_file',	__NAMESPACE__ . '\\' . '_pre_move_uploaded_file_UploadImage' );
	remove_filter( 'wp_unique_filename',		__NAMESPACE__ . '\\' . '_wp_unique_filename_UploadImage', 1, 4 );

	@unlink( $fileNamePathTmp );

	if( $postId )
	{
		$post = $post_prev;
		$post_id = $post_id_prev;
	}

	return( $res );
}

function _wp_unique_filename_UploadImage( $filename, $ext, $dir, $unique_filename_callback )
{
	global $ctxUploadImage;

	if( $ctxUploadImage[ 'overwrite' ] )
		$filename = $ctxUploadImage[ 'fileName' ];
	else
		Fs::CreateEmptyFile( $dir . '/' . $filename );

	return( $filename );
}

function _pre_move_uploaded_file_UploadImage( $move_new_file, $file, $new_file, $type )
{
	global $ctxUploadImage;

	if( @rename( $file[ 'tmp_name' ], $new_file ) === false )
		return( $move_new_file );

	return( true );
}

function _handle_upload_UploadImage( $info, $action )
{
	global $ctxUploadImage;

	$ctxUploadImage[ 'url' ] = $info[ 'url' ];

	if( !$ctxUploadImage[ 'addToAttachments' ] )
		$info[ 'error' ] = 'okWithoutPutAttachment';

	return( $info );
}

function _UploadImage( $fileNamePathTmp, $fileName, $contentType, $data, $postId, $addToAttachments, $overwrite )
{
	global $ctxUploadImage;

	$fileNamePathTmpSize = 0;
	{
		$file = @fopen( $fileNamePathTmp, 'wb' );
		if( $file === false )
			return( new WP_Error( 'internal_error', 'Can\'t create the file' ) );

		if( Fs::StreamCopy( $data, $file ) != Gen::S_OK )
			$err = new WP_Error( 'internal_error', 'Can\'t copy stream' );

		fclose( $file );
		if( $err )
			return( $err );
	}

	$_FILES[ 'f' ] = array(
		'name'					=> $fileName,
		'tmp_name'				=> $fileNamePathTmp,
		'type'					=> $contentType,
		'size'					=> $fileNamePathTmpSize,
		'error'					=> 0,
	);

	$_FILES[ 'f' ] = apply_filters( 'wp_handle_upload_prefilter', $_FILES[ 'f' ] );

	// MBI!!!!!!!!!!!! if $overwrite & $addToAttachments then update attachment - not create new

	$attachment_id = media_handle_upload( 'f', $postId, array(), array( 'test_form' => false, 'action' => 'wp_handle_sideload' ) );
	if( is_wp_error( $attachment_id ) )
	{
		if( !( $attachment_id -> get_error_code() == 'upload_error' && $attachment_id -> get_error_message() == 'okWithoutPutAttachment' ) )
			return( $attachment_id );
	}
	else
	{
		$attachment = wp_prepare_attachment_for_js( $attachment_id );
		if( !$attachment )
			return( new WP_Error( 'internal_error', 'wp_prepare_attachment_for_js failed' ) );
	}

	return( $ctxUploadImage[ 'url' ] );
}

// #######################################################################
// #######################################################################
